package plgdb

import (
	"dgo/MyProj/PrjDBUtils"
	"dgo/MyProj/PrjHttpServ"
	"dgo/goutils/utils"
	"fmt"
	"gitee.com/ymofen/supervalue"
	"strings"
	"time"
)

type PlgDBHelperBK struct {
	ObjectID             string
	dbres_file           string
	dbres_url            string
	dbres_prefix         string
	default_datasourceid string

	RegisterWebApiFunc   func(api_prefix string)
	UnRegisterWebApiFunc func(api_prefix string)
}

func NewPlgDBHelperBK() *PlgDBHelperBK {
	rval := &PlgDBHelperBK{}
	return rval
}

func (this *PlgDBHelperBK) NewDAOHelper(datasourceid string) *PrjDBUtils.DAOHelper {
	if len(datasourceid) == 0 {
		return PrjDBUtils.NewDAOHelper(this.default_datasourceid)
	} else {
		return PrjDBUtils.NewDAOHelper(datasourceid)
	}
}

/*
*

	  {
		  "id": "db-helper",
		  "type": "db.helper",
		  "conf": {
			"datasource":[
			  {"id":"kpl-vrs", "drivername":"mysql", "connstring":"admin:WXvrs@admin!@#1@tcp(119.96.188.188:3306)/gnss-vrs?charset=utf8&parseTime=true&loc=Local"},
			  {"id":"dcloud", "drivername":"mysql", "connstring":"admin:WXvrs@admin!@#1@tcp(119.96.188.188:3306)/dcloud?charset=utf8&parseTime=true&loc=Local"}
			],
			"db-res-delay-secs": 1,   // 延迟加载
			"db-res-file":"db.res",
			"db-res-prefix":"xxx",    // 所有id之前都加 xxx
			"db-res-url":"http://127.0.0.1:3000/plug/do?id=dcloud&accesstoken=kpl&action=pack&projectid=kpl-cloud",
	        "api-prefix":"/api/web/",  // 注册API地址 如果没有指定则使用插件方式访问, 尾部应该加入"/"
	        "default-datasourceid":"dcloud",
			"dbres":[
			  {
				"id":"vrs-batch", "conf":{
				   "$sql":{
					 "sql":"update caster_ntripsvr set fstate=$state$ where fsubnet='$subnet$'"
					}
				 }
			  }
			]
	  }
*/
func (this *PlgDBHelperBK) ReloadConf(conf *wrapper.SuperValue) (err error) {
	if len(this.ObjectID) == 0 {
		this.ObjectID = fmt.Sprintf("%.4X", utils.NewObjectDNA())
	}

	PrjDBUtils.LoadDataSourceConfig(conf.ValueByName("datasource"))

	conf.CheckExistsStrFunc("default-datasourceid", func(strv string) {
		this.default_datasourceid = strv
	})

	dbres_file_flag := 0
	conf.CheckStrFunc("db-res-file", func(strv string) {
		if this.dbres_file != strv {
			PrjHttpServ.DBResCleanEx(0, this.ObjectID)
			this.dbres_file = strv
			dbres_file_flag = 1
		}
	})

	conf.CheckStrFunc("db-res-url", func(strv string) {
		this.dbres_url = strv
	})

	conf.CheckStrFunc("db-res-prefix", func(strv string) {
		if this.dbres_prefix != strv {
			PrjHttpServ.DBResCleanEx(0, this.ObjectID)
			this.dbres_prefix = strv
			dbres_file_flag = 1
		}
	})

	if dbres_file_flag == 1 {
		this.ReloadDBRes()
	}

	PrjHttpServ.RegisterDBResList(this.dbres_prefix, conf.ValueByName("dbres"), 1, this.ObjectID)

	return
}

func (this *PlgDBHelperBK) ReloadFromUrl() (int, error) {
	err := PrjHttpServ.DownResFromServ(this.dbres_url, this.dbres_file, "")
	if err != nil {
		return 0, err
	} else {
		return PrjHttpServ.RegisterDBResFromFile(this.dbres_prefix, this.dbres_file, 0, this.ObjectID)
	}
}

func (this *PlgDBHelperBK) innerRelease() {
	PrjHttpServ.DBResClean(this.ObjectID)
}

func (this *PlgDBHelperBK) ReloadDBRes() (int, error) {
	n, err := PrjHttpServ.RegisterDBResFromFile(this.dbres_prefix, this.dbres_file, 0, this.ObjectID)
	if err != nil || n == 0 {
		time.AfterFunc(time.Second, func() { // 延迟加载
			this.ReloadFromUrl()
		})
		return 0, nil
	}
	return n, err
}

func (this *PlgDBHelperBK) innerGetVar(key string) (bool, interface{}) {
	return false, nil
}

func (this *PlgDBHelperBK) checkVarByResConf(conf *wrapper.SuperValue) (ret bool, valconf *wrapper.SuperValue) {
	if conf == nil {
		return true, nil
	}

	ret = true
	conf.Range(func(key string, val *wrapper.SuperValue) bool {
		if ok, v := this.innerGetVar(key); ok {
			strv := utils.GetStrValue(v, "")
			matchV := val.StringByName("value", "")
			if matchV == VAR_NOT_EMPTY {
				if len(strv) == 0 {
					ret = false
					valconf = val
					return false
				}
			} else if matchV == strv || strings.Contains(matchV+",", strv+",") {
				return true
			} else {
				ret = false
				valconf = val
				return false
			}
			return true
		} else {
			ret = false
			valconf = val
			return false
		}
	})
	return
}

func (this *PlgDBHelperBK) QryListByDBRes(req *wrapper.SuperValue, resp *wrapper.SuperValue) (errcode int, err error) {
	resid := req.StringByName("__resid", "")
	if len(resid) == 0 {
		err = fmt.Errorf("缺少资源ID")
		errcode = ERR_IN_PARAM_INVALID
		return
	}

	dbres := PrjHttpServ.GetDBRes(resid)

	if dbres == nil {
		return ERR_INNER, fmt.Errorf("无法找到对应的数据资源[%s]", resid)
	}

	if ok, itm := this.checkVarByResConf(dbres.ValueByName("check")); !ok {
		errcode = ERR_IN_PARAM_INVALID
		code := itm.IntByName("errcode", 0)
		msg := itm.StringByName("msg", "")
		if code != 0 {
			errcode = code
		}
		err = fmt.Errorf(msg)
		return
	}

	return
}
